<template>
  <div class="home">
    <el-row
      class="ffirst"
      style="width: auto; padding-top: 5%"
      v-show="inSearch"
    >
      <el-col :span="12" :offset="6"><h1 class="slogan">心语解惑</h1></el-col>
    </el-row>
    <el-row
      v-show="inSearch"
      class="fthird"
      style="width: auto; margin-top: 5px"
    >
      <el-col :span="16" :offset="4">
        <div class="txt" ref="chatTxt">
          <div
            class="cancelBu"
            style="display: flex; align-items: flex-start; margin-bottom: 8px"
          >
            <el-button circle size="small" color="#353b46" @click="cancel()"
              ><el-icon><Close /></el-icon
            ></el-button>
          </div>
          <div class="chat-wrapper">
            <chat-item
              v-for="item in chatItems"
              :key="item.timeStamp"
              :message="item.message"
              :timeStamp="item.timeStamp"
              :from="item.from"
              :loading="item.loading"
            ></chat-item>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row
      class="first"
      style="width: auto; padding-top: 10%; padding-bottom: 3%"
      v-show="!inSearch"
    >
      <el-col :span="12" :offset="6"><h1 class="slogan">心语解惑</h1></el-col>
    </el-row>
    <el-row class="second" style="width: auto">
      <el-col :span="16" :offset="4">
        <el-input
          @focus="handleInputFocus"
          @blur="handleInputBlur"
          placeholder="请输入文字或点击左侧麦克风按钮进行提问吧~"
          v-model="info"
          clearable
          @keyup.enter="generate()"
        >
          <template #prefix>
            <div id="voice"></div>
            <div class="voice-input-button-wrapper">
              <voice-input-button
                appId="c5d5f287"
                apiKey="7a6d716e393d7eca139540949a397323"
                apiSecret="MTE3MThhMmViY2ZjNDhmZWRlMzkyZDQz"
                color="#ACAFB6"
                tipPosition="top"
                interactiveMode="touch"
                v-model="result"
                :record="showResult"
                :record-start="recordStart"
                :record-stop="recordStop"
                :record-blank="recordNoResult"
                :record-failed="recordFailed"
                :record-ready="recordReady"
                :record-complete="recordComplete"
              >
                <template v-slot:no-speak>没听清您说的什么</template>
              </voice-input-button>
              <!-- <el-icon class="el-input__icon" :size="20"><search /></el-icon> -->
            </div>
          </template>
          <template #append>
            <el-button class="phoneCode" @click="generate()">提问</el-button>
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-row v-show="!inSearch" class="third" style="width: auto">
      <el-col :span="16" :offset="4">
        <div style="margin-top: 3px">
          <div
            class="txt2"
            style="
              color: #c7a46c;
              font-weight: 50;
              letter-spacing: 2px;
              margin-top: 30px;
            "
          >
            您想要的，在这里都能搜到！
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script name="ChatView">
import {
  getCurrentInstance,
  defineComponent,
  ref,
  toRefs,
  reactive,
  onMounted,
} from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import voiceInputButton from "voice-input-button2";
import { Vue2InVue3 } from "@efox/emp-vuett";
import ChatItem from "../components/ChatItem.vue";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Close,
} from "@element-plus/icons-vue";
const ContentInVue3 = Vue2InVue3(voiceInputButton, "voice");

export default {
  name: "App",

  components: {
    "voice-input-button": ContentInVue3,
    "chat-item": ChatItem,
    Close,
  },
  // mounted() {
  //   this.scrollToBottom();
  // },
  // updated() {
  //   this.scrollToBottom();
  // },
  data() {
    return {
      info: "",
      loading: false,
      ans: "",
      inSearch: false,
      api: "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",
      result: "",
      chatItems: [],
      txtArr: [{ role: "system", content: "You are a helpful assistant." }],
    };
  },

  methods: {
    scrollToBottom: function () {
      this.$nextTick(() => {
        var container = this.$el.querySelector(".txt");
        container.scrollTop = container.scrollHeight;
      });
    },
    generate() {
      //   const { proxy } = getCurrentInstance();
      //   console.log(proxy);
      var txt;

      console.log("generate");
      if (this.info == "") {
        ElMessage({
          message: "请输入您的问题",
          type: "warning",
          offset: 80,
        });
        return;
      }
      //   var first = document.querySelector(".first");
      //   first.style.transform = "translate(0, 30px)";
      //   first.style.transition = "all  2.25s  ease-in";
      var second = document.querySelector(".second");
      second.style.transform = "translate(0, 30px)";
      second.style.transition = "all  1.25s  ease-in";
      var third = document.querySelector(".fthird");
      third.style.transform = "translate(0, -5px)";
      third.style.transition = "all  1.25s  ease-in";
      // js实现滚动条实时到最底部
      // this.chatItems.forEach((item) => {
      //   if (item.from == 1) {
      //     txtArr.push({ role: "user", content: item.message });
      //   }
      //   if (item.from == 2) {
      //     txtArr.push({ role: "assistant", content: item.message });
      //   }
      // });
      this.chatItems.push({
        message: this.info,
        from: 1,
        timeStamp: new Date().toLocaleString(),
        loading: false,
      });
      this.txtArr.push({ role: "user", content: this.info });
      txt = this.info;
      this.info = "";
      this.ans = "";
      this.loading = true;
      this.inSearch = true;
      this.chatItems.push({
        message: "",
        from: 2,
        timeStamp: new Date().toLocaleString(),
        loading: true,
      });
      this.scrollToBottom();

      this.$axios({
        url: "https://api.openai.com/v1/chat/completions",
        method: "post",
        data: {
          // max_tokens: 4000,
          model: "gpt-3.5-turbo",
          messages: this.txtArr,
          temperature: 0.7,
          top_p: 1,
          frequency_penalty: 0,
          presence_penalty: 0,
        },
        headers: {
          "content-type": "application/json",
          Authorization: "Bearer " + this.api,
        },
      })
        .then((res) => {
          console.log(res);
          let tmpans = res.data.choices[0].message.content;
          if (
            tmpans[0] == "?" ||
            tmpans[0] == "？" ||
            tmpans[0] == "。" ||
            tmpans[0] == "！" ||
            tmpans[0] == "，"
          ) {
            tmpans = tmpans.substring(1, tmpans.length);
          }
          // 去除文本前后空格换行
          tmpans = tmpans.trim();
          //   console.log(tmpans);
          this.ans = tmpans;
          console.log(this.ans);
          this.chatItems[this.chatItems.length - 1].loading = false;
          this.chatItems[this.chatItems.length - 1].message = this.ans;
          this.txtArr.push({ role: "assistant", content: this.ans });
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    cancel() {
      this.inSearch = false;
      this.info = "";
      this.ans = "";
      // var first = document.querySelector(".first");
      // first.style.transform = "";
      // first.style.transition = "all  1.25s  ease-in";
      var second = document.querySelector(".second");
      second.style.transform = "";
      second.style.transition = "all  1.25s  ease-in";
      // var third = document.querySelector(".third");
      // third.style.transform = "";
      // third.style.transition = "all  1.25s  ease-in";
      this.chatItems = [];
      this.txtArr = [
        { role: "system", content: "You are a helpful assistant." },
      ];
    },
    recordReady: function () {
      console.info("按钮就绪!");
    },
    recordStart: function () {
      console.info("录音开始");
    },
    showResult: function (text) {
      console.info("收到识别结果：", text);
    },
    recordStop: function () {
      console.info("录音结束");
    },
    recordNoResult: function () {
      console.info("没有录到什么，请重试");
    },
    recordComplete: function (text) {
      console.info("识别完成! 最终结果：", text);
      this.info = text;
    },

    recordFailed: function (error) {
      console.info("识别失败，错误栈：", error);
    },
    handleInputFocus() {
      let appendEle = document.getElementsByClassName(
        "el-input-group__append"
      )[0];
      var apele = appendEle;
      apele.style.borderColor = "#4568ee";
    },
    handleInputBlur() {
      let appendEle = document.getElementsByClassName(
        "el-input-group__append"
      )[0];
      var apele = appendEle;
      apele.style.borderColor = "#DCDFE6";
    },
  },
};
</script>
<style lang="less" scoped>
@font-face {
  font-family: "Zhu";
  src: url("../assets/fonts/MaokenZhuyuanTi.ttf");
}
/deep/ .el-input {
  color: #a6adba;
  --el-input-border-color: #2a303c;
  --el-input-bg-color: #2a303c;
  height: 50px;
  --el-input-focus-border-color: #404955;
}

/deep/ .el-input__inner {
  color: #a6adba;
  font-weight: 50;
  font-size: 1.1rem;
  font-family: "Zhu", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
    Liberation Mono, Courier New, monospace;
}

/deep/.el-input-group__append {
  background-color: #191d24;
  box-shadow: none;
  font-weight: 50;
  font-size: 1rem;
  font-family: "Zhu", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
    Liberation Mono, Courier New, monospace;
}
.logo {
  width: 25vh;
  height: 15vh;
  margin: 0 auto;
  z-index: 1;
}
@keyframes scale-up {
  0% {
    opacity: 0;
    transform: scale(0.2);
  }

  100% {
    opacity: 1;
    transform: scale(1);
  }
}
.home {
  background: linear-gradient(rgba(14, 14, 14, 0.7), rgba(0, 0, 0, 0.7)),
    url(../assets/bg.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  opacity: 0.95;
  height: 100%;
  min-height: 100%;
  overflow: auto;
}
/deep/.el-skeleton.is-animated .el-skeleton__item {
  background: linear-gradient(90deg, #5e6570 25%, #a6adba 37%, #a6adba 63%);
  background-size: 400% 100%;
  animation: el-skeleton-loading 1.4s ease infinite;
}
.txt {
  //   background-color: #363b46;
  background-color: rgba(0, 0, 0, 0.4);
  //   border-radius: 25px;
  box-shadow: 0px 0px 10px 5px rgb(0 0 0 / 70%);
  height: auto;
  max-height: 50vh;
  border-radius: 10px;
  padding: 1% 5%;
  overflow: auto;
  line-height: 4vh;
  text-align: justify;
  white-space: pre-wrap;
  animation-name: scale-up;
  color: #a6adba;
  font-weight: 400;
  font-size: 1.1rem;
  margin-top: 5%;
}
.slogan {
  font-family: "Zhu", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
    Liberation Mono, Courier New, monospace;
  font-weight: 100;
  letter-spacing: 10px;
  font-size: 4.5rem;
  line-height: 1;
  color: #c7a46c;
}
//   .txt:hover {
//     overflow-y: auto;
//   }
.txt {
  /*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/
  // 滚动条整体部分
  &::-webkit-scrollbar {
    width: 6px;
    height: 3px;
  }
  // 滚动条的轨道的两端按钮，允许通过点击微调小方块的位置。
  &::-webkit-scrollbar-button {
    display: none;
  }
  &::-webkit-scrollbar-track {
    // background-color: rgb(42, 44, 48 / 46%);
    background: transparent;
    border-radius: 10px;
  }
  // 滚动条里面的小方块，能向上向下移动（或往左往右移动，取决于是垂直滚动条还是水平滚动条）
  &::-webkit-scrollbar-thumb {
    background: #81878f;
    cursor: pointer;
    border-radius: 10px;
  }
}
/*定义滚动条宽高及背景，宽高分别对应横竖滚动条的尺寸*/
// 滚动条整体部分
::-webkit-scrollbar {
  width: 8px;
  height: 3px;
}
// 滚动条的轨道的两端按钮，允许通过点击微调小方块的位置。
::-webkit-scrollbar-button {
  display: none;
}
::-webkit-scrollbar-track {
  background-color: rgb(42, 44, 48 / 46%);
  border-radius: 10px;
}
// 滚动条里面的小方块，能向上向下移动（或往左往右移动，取决于是垂直滚动条还是水平滚动条）
::-webkit-scrollbar-thumb {
  background: #81878f;
  cursor: pointer;
  border-radius: 10px;
}

// .message-wrapper {
//   display: flex;
//   align-items: flex-start;
//   padding-bottom: 20px;
// }
// .message-wrapper.reverse {
//   justify-content: flex-end;
// }
// .message-wrapper.reverse .message-box {
//   background-color: #1c2c4c;
//   color: #fff;
// }
// .message-wrapper.reverse .message-box-wrapper {
//   display: flex;
//   flex-direction: column;
//   align-items: flex-end;
// }
// .message-wrapper.reverse .message-pp {
//   order: 2;
// }

// .message-pp {
//   width: 40px;
//   height: 40px;
//   border-radius: 50%;
//   object-fit: cover;
//   flex-shrink: 0;
// }

// .message-box {
//   background-color: #576c99;
//   box-shadow: rgba(18, 23, 45, 0.6) 0px 8px 24px;
//   border-radius: 4px;
//   padding: 10px;
//   font-size: 12px;
//   line-height: 16px;
//   width: auto;
//   max-width: 80%;
//   color: #fff;
// }
// .message-box-wrapper {
//   margin: 0 12px;
// }
// // .message-box-wrapper span {
// //   font-size: 10px;
// //   line-height: 16px;
// //   color: rgba(255, 255, 255, 1);
// //   opacity: 0.6;
// // }
</style>
